package org.jeecg.modules.stOrder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.stCaip.entity.HqStCaip;
import org.jeecg.modules.stCaip.service.IHqStCaipService;
import org.jeecg.modules.stChuangK.entity.HqStChuangk;
import org.jeecg.modules.stChuangK.service.IHqStChuangkService;
import org.jeecg.modules.stOrder.entity.HtStOrder;
import org.jeecg.modules.stOrder.entity.HtStOrderDetail;
import org.jeecg.modules.stOrder.service.IHtStOrderDetailService;
import org.jeecg.modules.stOrder.service.IHtStOrderService;
import org.jeecg.modules.stOrder.vo.HtStOrderPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 食堂订单
 * @Author: jeecg-boot
 * @Date: 2020-06-01
 * @Version: V1.0
 */
@Api(tags = "食堂订单")
@RestController
@RequestMapping("/stOrder/htStOrder")
@Slf4j
public class HtStOrderController {
    @Autowired
    private IHtStOrderService htStOrderService;
    @Autowired
    private IHtStOrderDetailService htStOrderDetailService;
    @Autowired
    private IHqStCaipService hqStCaipService;
    @Autowired
    private IHqStChuangkService hqStChuangkService;

    // 手机端下单简化传入参数，这里根据各种id自动补齐
    @PostMapping(value = "/add4App")
    public Result<?> add4App(@RequestBody HtStOrderPage htStOrderPage) {
        int count = htStOrderService.count() + 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
        String orderNo = htStOrderPage.getChuangkId() + "_" + sdf.format(new Date()) + "_" + count;
        htStOrderPage.setOrderno(orderNo);
        htStOrderPage.setStatus("1");
        htStOrderPage.setCreateTime(new Date());

        double mony = 0.0;
        for (HtStOrderDetail htStOrderDetail : htStOrderPage.getHtStOrderDetailList()
        ) {
            htStOrderDetail.setChuangkId(htStOrderPage.getChuangkId());
            HqStChuangk hqStChuangk = hqStChuangkService.getById(htStOrderPage.getChuangkId());
            if (hqStChuangk != null)
                htStOrderDetail.setChuangkName(hqStChuangk.getName());

            htStOrderDetail.setOrderNo(orderNo);
            HqStCaip hqStCaip = hqStCaipService.getById(htStOrderDetail.getCaipId());
            if (hqStCaip != null) {
                htStOrderDetail.setCaipName(hqStCaip.getName());
                htStOrderDetail.setCaipPicture(hqStCaip.getPicture());
                htStOrderDetail.setPrice(hqStCaip.getPrice() + "");
                htStOrderDetail.setCreateTime(new Date());
                htStOrderDetail.setSumprice((hqStCaip.getPrice() * Integer.parseInt(htStOrderDetail.getAmout()) + ""));
                mony += Double.parseDouble(htStOrderDetail.getSumprice());
            }

        }

        htStOrderPage.setMony(mony + "");

        HtStOrder htStOrder = new HtStOrder();
        BeanUtils.copyProperties(htStOrderPage, htStOrder);
        htStOrderService.saveMain(htStOrder, htStOrderPage.getHtStOrderDetailList());
        return Result.ok("添加成功！");
    }

    /**
     * 分页列表查询
     *
     * @param htStOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "食堂订单-分页列表查询")
    @ApiOperation(value = "食堂订单-分页列表查询", notes = "食堂订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HtStOrder htStOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HtStOrder> queryWrapper = QueryGenerator.initQueryWrapper(htStOrder, req.getParameterMap());
        Page<HtStOrder> page = new Page<HtStOrder>(pageNo, pageSize);
        IPage<HtStOrder> pageList = htStOrderService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param htStOrderPage
     * @return
     */
    @AutoLog(value = "食堂订单-添加")
    @ApiOperation(value = "食堂订单-添加", notes = "食堂订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HtStOrderPage htStOrderPage) {
        HtStOrder htStOrder = new HtStOrder();
        BeanUtils.copyProperties(htStOrderPage, htStOrder);
        htStOrderService.saveMain(htStOrder, htStOrderPage.getHtStOrderDetailList());
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param htStOrderPage
     * @return
     */
    @AutoLog(value = "食堂订单-编辑")
    @ApiOperation(value = "食堂订单-编辑", notes = "食堂订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HtStOrderPage htStOrderPage) {
        HtStOrder htStOrder = new HtStOrder();
        BeanUtils.copyProperties(htStOrderPage, htStOrder);
        HtStOrder htStOrderEntity = htStOrderService.getById(htStOrder.getId());
        if (htStOrderEntity == null) {
            return Result.error("未找到对应数据");
        }
        htStOrderService.updateMain(htStOrder, htStOrderPage.getHtStOrderDetailList());
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "食堂订单-通过id删除")
    @ApiOperation(value = "食堂订单-通过id删除", notes = "食堂订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        htStOrderService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "食堂订单-批量删除")
    @ApiOperation(value = "食堂订单-批量删除", notes = "食堂订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.htStOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "食堂订单-通过id查询")
    @ApiOperation(value = "食堂订单-通过id查询", notes = "食堂订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HtStOrder htStOrder = htStOrderService.getById(id);
        if (htStOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(htStOrder);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单详情通过主表ID查询")
    @ApiOperation(value = "订单详情主表ID查询", notes = "订单详情-通主表ID查询")
    @GetMapping(value = "/queryHtStOrderDetailByMainId")
    public Result<?> queryHtStOrderDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<HtStOrderDetail> htStOrderDetailList = htStOrderDetailService.selectByMainId(id);
        return Result.ok(htStOrderDetailList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param htStOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HtStOrder htStOrder) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<HtStOrder> queryWrapper = QueryGenerator.initQueryWrapper(htStOrder, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<HtStOrder> queryList = htStOrderService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<HtStOrder> htStOrderList = new ArrayList<HtStOrder>();
        if (oConvertUtils.isEmpty(selections)) {
            htStOrderList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            htStOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<HtStOrderPage> pageList = new ArrayList<HtStOrderPage>();
        for (HtStOrder main : htStOrderList) {
            HtStOrderPage vo = new HtStOrderPage();
            BeanUtils.copyProperties(main, vo);
            List<HtStOrderDetail> htStOrderDetailList = htStOrderDetailService.selectByMainId(main.getId());
            vo.setHtStOrderDetailList(htStOrderDetailList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "食堂订单列表");
        mv.addObject(NormalExcelConstants.CLASS, HtStOrderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("食堂订单数据", "导出人:" + sysUser.getRealname(), "食堂订单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<HtStOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), HtStOrderPage.class, params);
                for (HtStOrderPage page : list) {
                    HtStOrder po = new HtStOrder();
                    BeanUtils.copyProperties(page, po);
                    htStOrderService.saveMain(po, page.getHtStOrderDetailList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
